
package com.yicong.ants.ui.order;

import android.app.AlertDialog;
import android.app.Dialog;
import android.view.View;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;

import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.PrefHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.StringHelper;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.order.OrderAdapterBean;
import com.yicong.ants.databinding.DialogUserIdInfoEditBinding;
import com.yicong.ants.databinding.DialogVisitorAddEditBinding;
import com.yicong.ants.databinding.SubmitOrderActivityBinding;
import com.yicong.ants.databinding.SubmitOrderVisitorItemBinding;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.ViewHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提交订单
 *
 * @author cchao
 * @version 2019-08-22.
 */
public class SubmitOrderActivity extends BaseTitleBarActivity<SubmitOrderActivityBinding> implements View.OnClickListener {
    OrderAdapterBean mBean;
    List<OrderAdapterBean.VisitorInfo> mVisitors;
    Map<String, OrderAdapterBean.VisitorInfo> mHistoryInput;

    @Override
    protected int getLayout() {
        return R.layout.submit_order_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleText("确认订单");
        mDataBind.setClick(this);
        mBean = JsonHelper.toObject(getIntent().getStringExtra(Constants.Extra.JSON), OrderAdapterBean.class);
        mDataBind.setBean(mBean);
        mVisitors = new ArrayList<>();
        Logs.logEvent("游客列表： " + PrefHelper.getString(Constants.Prefs.Visitor_History_Input, "{}"));
        mHistoryInput = JsonHelper.toMap(PrefHelper.getString(Constants.Prefs.Visitor_History_Input, "{}"), OrderAdapterBean.VisitorInfo.class);
        mBean.setMVisitorsInfo(mVisitors);
        initView();
    }

    private void initView() {
        mDataBind.discountCheck.setOnCheckedChangeListener((buttonView, isChecked) -> toggleDiscount(isChecked));
        mDataBind.discountCheck.post(() -> {
            RxHelper.timerConsumer(100, aLong -> {
                //
                mDataBind.discountCheck.post(() -> {
                    mDataBind.discountCheck.setChecked(mBean.isCheckDiscount());
                });
            });
        });
        // 添加绑卡用户,如果没有则要求添加
        if (StringHelper.isEmpty(UserManager.getUserBean().getId_card_num())) {
            showToast("请先绑定你的身份信息");
            editUserIdCardInfo();
            return;
        }
        mVisitors.add(new OrderAdapterBean.VisitorInfo()
            .setMobile(UserManager.getUserBean().getMobile())
            .setName(UserManager.getUserBean().getId_card_name())
            .setId_num(UserManager.getUserBean().getId_card_num()));
        updateVisitors();
    }

    private void editUserIdCardInfo() {
        DialogUserIdInfoEditBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.dialog_user_id_info_edit, null, false);
        binding.mobile.setText(UserManager.getMobile());
        Dialog dialog = new AlertDialog.Builder(mContext)
            .setView(binding.getRoot())
            .setCancelable(false)
            .setPositiveButton("确定", (dialog2, which) -> {
                if (ViewHelper.checkInputFail(binding.name, "请输入身份证姓名")) {
                    return;
                }
                if (ViewHelper.checkInputFail(binding.idNum, "请输入身份证号")) {
                    return;
                }

                Map<String, String> map = new HashMap<>();
                map.put("id_card_name", binding.name.getText().toString());
                map.put("id_card_num", binding.idNum.getText().toString());
                showProgress();
                addSubscribe(RetrofitHelper.getApis().editIdCardInfo(map)
                    .compose(RxHelper.toMain())
                    .subscribe(respBean -> {
                        hideProgress();
                        if (respBean.isCodeFail()) {
                            showToast(respBean.getMsg());
                            return;
                        }
                        UserManager.updateUserBean(respBean.getData());
                        OrderAdapterBean.VisitorInfo visitorInfo = new OrderAdapterBean.VisitorInfo();
                        visitorInfo.setName(binding.name.getText().toString())
                            .setId_num(binding.idNum.getText().toString())
                            .setMobile(binding.mobile.getText().toString());

                        addVisitor(visitorInfo);
                        dialog2.dismiss();
                    }, RxHelper.getErrorTextConsumer(this)));
            }).create();
        dialog.show();
    }

    private void toggleDiscount(boolean isChecked) {
        mBean.setCheckDiscount(isChecked);
        if (isChecked) {
            mDataBind.discountPrice.setText("￥" + mBean.getDiscount());
            mDataBind.totalPriceBottom.setText("￥" + mBean.getCurrentPrice());
        } else {
            mBean.setUnitPrice(mBean.getOriginalPrice());
            mDataBind.discountPrice.setText("￥-0.0");
            mDataBind.totalPriceBottom.setText("￥" + mBean.getOriginalPrice());
        }
        mBean.updateTotalAmount();
        mDataBind.setBean(mBean);
    }

    @Override
    protected void onLoadData() {

    }

    public void addVisitor(OrderAdapterBean.VisitorInfo visitorInfo) {
        if (mVisitors.contains(visitorInfo)) {
            return;
        }

        mVisitors.add(visitorInfo);
        mHistoryInput.put(visitorInfo.getName(), visitorInfo);
        PrefHelper.putString(Constants.Prefs.Visitor_History_Input, JsonHelper.toJson(mHistoryInput));
        updateVisitors();
    }

    public void updateVisitors() {
        mDataBind.visitorLinear.removeAllViews();
        for (OrderAdapterBean.VisitorInfo info : mVisitors) {
            SubmitOrderVisitorItemBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.submit_order_visitor_item, mDataBind.visitorLinear, false);
            binding.setBean(info);
            binding.setClick(v -> {
                switch (v.getId()) {
                    case R.id.remove_visitor:
                        mVisitors.remove(info);
                        mHistoryInput.remove(info.getName());
                        PrefHelper.putString(Constants.Prefs.Visitor_History_Input, JsonHelper.toJson(mHistoryInput));
                        updateVisitors();
                        if (mVisitors.size() == 0) {
                            onShowAddVisitorDialog(null);
                        }
                        break;
                    case R.id.edit:
                        onShowAddVisitorDialog(info);
                        break;
                }
            });
            mDataBind.visitorLinear.addView(binding.getRoot());
        }
        mBean.updateTotalAmount();
        mDataBind.setBean(mBean);
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Pay_Result_Turn:
                finish();
                break;
        }
    }

    /**
     * 显示游客信息填写和编辑页
     *
     * @param bean 为空为新增，
     */
    private void onShowAddVisitorDialog(OrderAdapterBean.VisitorInfo bean) {
        DialogVisitorAddEditBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.dialog_visitor_add_edit, null, false);
        if (bean != null) {
            binding.setBean(bean);
        }

        //region 填充历史数据
        for (Map.Entry<String, OrderAdapterBean.VisitorInfo> visitorInfo : mHistoryInput.entrySet()) {
            // 如果已经存在就不显示
            boolean hasInput = false;
            for (OrderAdapterBean.VisitorInfo has : mBean.getMVisitorsInfo()) {
                if (has.getName().equals(visitorInfo.getKey())) {
                    hasInput = true;
                    break;
                }
            }
            if (hasInput) {
                continue;
            }
            View item = mLayoutInflater.inflate(R.layout.submit_order_visitor_history_item, null);
            TextView textView = item.findViewById(R.id.text);
            textView.setText(visitorInfo.getKey());
            item.setOnClickListener((c) -> {
                try {
                    binding.setBean(visitorInfo.getValue());
                } catch (Exception ex) {
                    Logs.logException(ex);
                }
            });
            binding.historyInput.addView(item);
        }
        if (binding.historyInput.getChildCount() == 0) {
            UiHelper.setVisibleElseGone(binding.historyInput, false);
        }
        //endregion

        //region 编辑 游客信息
        Dialog dialog = new AlertDialog.Builder(mContext)
            .setView(binding.getRoot())
            .setPositiveButton("确定", (dialog2, which) -> {
                if (ViewHelper.checkInputFail(binding.name, "请输入游客姓名")) {
                    return;
                }
                if (ViewHelper.checkInputFail(binding.idNum, "请输入游客身份号")) {
                    return;
                }

                OrderAdapterBean.VisitorInfo visitorInfo = bean;
                if (visitorInfo == null) {
                    visitorInfo = new OrderAdapterBean.VisitorInfo();
                }

                visitorInfo.setName(binding.name.getText().toString())
                    .setId_num(binding.idNum.getText().toString())
                    .setMobile(binding.mobile.getText().toString());

                addVisitor(visitorInfo);
            }).create();
        dialog.show();
        //endregion
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.subtract:
                mVisitors.remove(mVisitors.size() - 1);
                updateVisitors();
                break;
            case R.id.add:
            case R.id.add_visitor:
                if (mBean.getGoodsType().equals(OrderAdapterBean.GoodsType.AdvanceScenic)) {
                    UiHelper.showToast("预约景区仅允许持卡人预约");
                    return;
                }
                onShowAddVisitorDialog(null);
                break;
            case R.id.apply:
                if (StringHelper.isEmpty(UserManager.getUserBean().getId_card_num())) {
                    showToast("请绑定你的身份证信息");
                    editUserIdCardInfo();
                    return;
                }
                if (mVisitors.isEmpty()) {
                    showToast("至少需要一个游客信息");
                    return;
                }
                String price = mBean.getOriginalPrice();
                if (mDataBind.discountCheck.isChecked()) {
                    price = mBean.getCurrentPrice();
                }
                mBean.setCheckDiscount(mDataBind.discountCheck.isChecked());
                mBean.setTotalAmount(String.valueOf(Float.parseFloat(price) * mVisitors.size()));

                Router.turnTo(mContext, PayOrderActivity2.class)
                    .putExtra(Constants.Extra.JSON, JsonHelper.toJson(mBean))
                    .start();

                break;
        }
    }
}
